/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.exec;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;

/**
 * Runs daemon processes asynchronously. Callers are expected to register a
 * {@link ProcessDestroyer} before executing any processes.
 *
 * @since 1.3
 */
public class DaemonExecutor extends DefaultExecutor {
	private static int counter = 0;
	private boolean useInternalExecutorService = true;
	private ScheduledExecutorService scheduledExecutorService;

	public DaemonExecutor() {
		super();
	}

	public DaemonExecutor(boolean redirectErrorStream) {
		super(redirectErrorStream);
	}

	/**
	 * Use latest @see java.util.concurrent.ExecutorService
	 * 
	 * @param executorService
	 */
	@Override
	protected void setScheduledExecutorService(final ScheduledExecutorService scheduledExecutorService) {
		if (scheduledExecutorService == null) {
			throw new java.lang.UnsupportedOperationException("ScheduledExecutorService must not be null");
		}

		if (scheduledExecutorService == this.scheduledExecutorService) {
			useInternalExecutorService = true;
		} else {
			useInternalExecutorService = false;
		}

		if (this.scheduledExecutorService != null) {
			if (useInternalExecutorService) {
				scheduledExecutorService.shutdown();
			}
		}
		this.scheduledExecutorService = scheduledExecutorService;
	}

	@Override
	protected ScheduledExecutorService getScheduledExecutorService() {
		if (this.scheduledExecutorService == null) {
			useInternalExecutorService = true;
			this.scheduledExecutorService = Executors.newScheduledThreadPool(4, new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					Thread t = new Thread(r);
					t.setName("Exec-Thread-"+(counter++));
					t.setDaemon(true);
					return t;
				}
			});
		}
		return this.scheduledExecutorService;
	}

}
